 <template>
	<view class="login-container">
		<!-- <custom-navbar title="登录" :showBack="true"></custom-navbar> -->
		
		<view class="main-content" :style="{paddingTop: navbarTotalHeight + 'px'}">
			<!-- Logo区域 -->
			<view class="logo-section">
				<image class="app-logo" :src="logo" mode="aspectFit"></image>
			   <view>
				<image class="app-name" :src="appname" mode="aspectFit"></image>
			   </view>					

				<!-- <text class="app-name">懒人资源</text> -->
				<!-- <text class="app-slogan">Lazy resources</text> -->
			</view>
			
			<!-- 手机登录表单 -->
			<view class="login-form">
				<view class="form-group">
					<image class="input-icon" src="https://img.icons8.com/ios/50/phone.png" mode="aspectFit"></image>
					<input 
						class="input-field" 
						placeholder="请输入手机号" 
						type="number" 
						v-model="phone"
						maxlength="11"
					/>
				</view>
				
				<view class="form-group" v-if="isLoginMode">
					<image class="input-icon" src="https://img.icons8.com/ios/50/lock.png" mode="aspectFit"></image>
					<input 
						class="input-field" 
						placeholder="请输入密码" 
						:password="!showPassword"
						v-model="password"
					/>
					<image 
						class="eye-icon" 
						:src="showPassword ? 'https://img.icons8.com/ios/50/visible.png' : 'https://img.icons8.com/ios/50/invisible.png'" 
						mode="aspectFit"
						@tap="togglePassword"
					></image>
				</view>
				
				<view class="form-group" v-else>
					<image class="input-icon" src="https://img.icons8.com/ios/50/sms.png" mode="aspectFit"></image>
					<input 
						class="input-field" 
						placeholder="请输入验证码" 
						v-model="verifyCode"
						maxlength="6"
					/>
					<view class="code-btn" @tap="sendCode" :class="{disabled: codeCountdown > 0}">
						<text class="code-text">
							{{codeCountdown > 0 ? `${codeCountdown}s` : '获取验证码'}}
						</text>
					</view>
				</view>
				
				<!-- 注册时的确认密码 -->
				<view class="form-group" v-if="!isLoginMode">
					<image class="input-icon" src="https://img.icons8.com/ios/50/lock.png" mode="aspectFit"></image>
					<input 
						class="input-field" 
						placeholder="请设置密码" 
						:password="!showPassword"
						v-model="password"
					/>
					<image 
						class="eye-icon" 
						:src="showPassword ? 'https://img.icons8.com/ios/50/visible.png' : 'https://img.icons8.com/ios/50/invisible.png'" 
						mode="aspectFit"
						@tap="togglePassword"
					></image>
				</view>
				
				<view class="form-group" v-if="!isLoginMode">
					<image class="input-icon" src="https://img.icons8.com/ios/50/lock.png" mode="aspectFit"></image>
					<input 
						class="input-field" 
						placeholder="请确认密码" 
						:password="!showConfirmPassword"
						v-model="confirmPassword"
					/>
					<image 
						class="eye-icon" 
						:src="showConfirmPassword ? 'https://img.icons8.com/ios/50/visible.png' : 'https://img.icons8.com/ios/50/invisible.png'" 
						mode="aspectFit"
						@tap="toggleConfirmPassword"
					></image>
				</view>
				<!-- 协议提示 -->
			<view class="agreement-section">
				<view class="agreement-check" @tap="toggleAgreement">
					<image 
						class="check-icon" 
						:src="agreed ? 'https://img.icons8.com/fluency/48/checked-checkbox.png' : 'https://img.icons8.com/ios/50/unchecked-checkbox.png'" 
						mode="aspectFit"
					></image>
					<text class="agreement-text">
						我已阅读并同意
						<text class="link-style" @tap.stop="showAgreement('user')">《用户协议》</text>
						和
						<text class="link-style" @tap.stop="showAgreement('privacy')">《隐私政策》</text>
					</text>
				</view>
			</view>
				<!-- 登录/注册按钮 -->
				<view class="submit-btn" @tap="handleSubmit">
					<text class="btn-text">{{isLoginMode ? '登录' : '注册'}}</text>
				</view>
				
				<!-- 操作链接 -->
				<view class="action-links">
					<text class="link-text" @tap="toggleMode">
						{{isLoginMode ? '还没有账号？立即注册' : '已有账号？立即登录'}}
					</text>
					<text class="link-text" @tap="goToForgotPassword" v-if="isLoginMode">忘记密码？</text>
				</view>
			</view>
			
			<!-- 分割线 -->
			<view class="divider">
				<view class="divider-line"></view>
				<text class="divider-text">其他登录方式</text>
				<view class="divider-line"></view>
			</view>
			
			<!-- 微信登录 -->
			<view class="wechat-login">
				<view class="wechat-btn" @tap="handleWechatLogin">
					<image class="wechat-icon" :src="weixin" mode="aspectFit"></image>
					<text class="wechat-text">微信登录</text>
				</view>
			</view>
			
			
		</view>
	</view>
</template>

<script>
import CustomNavbar from '@/components/custom-navbar/custom-navbar.vue';
import weixin from '@/static/icon/weixin.png'
import logo from '@/static/logo.png'
import appname from '@/static/appname.png'
export default {
	components: {
		CustomNavbar
	},
	data() {
		return {
			navbarTotalHeight: 132,
			statusBarHeight: 44,
			isLoginMode: true, // true: 登录, false: 注册
			phone: '',
			password: '',
			confirmPassword: '',
			verifyCode: '',
			showPassword: false,
			showConfirmPassword: false,
			codeCountdown: 0,
			agreed: false,
			codeTimer: null,
			weixin,
			logo,
			appname
		}
	},
	mounted() {
		const systemInfo = uni.getSystemInfoSync();
		this.statusBarHeight = systemInfo.statusBarHeight || 44;
		this.navbarTotalHeight = this.statusBarHeight + 44;
	},
	onUnload() {
		// 清理定时器
		if (this.codeTimer) {
			clearInterval(this.codeTimer);
		}
	},
	methods: {
		// 切换登录/注册模式
		toggleMode() {
			this.isLoginMode = !this.isLoginMode;
			this.clearForm();
		},
		
		// 清空表单
		clearForm() {
			this.phone = '';
			this.password = '';
			this.confirmPassword = '';
			this.verifyCode = '';
			this.showPassword = false;
			this.showConfirmPassword = false;
		},
		
		// 切换密码可见性
		togglePassword() {
			this.showPassword = !this.showPassword;
		},
		
		// 切换确认密码可见性
		toggleConfirmPassword() {
			this.showConfirmPassword = !this.showConfirmPassword;
		},
		
		// 发送验证码
		sendCode() {
			if (this.codeCountdown > 0) return;
			
			if (!this.phone) {
				uni.showToast({
					title: '请输入手机号',
					icon: 'none'
				});
				return;
			}
			
			if (!/^1[3-9]\d{9}$/.test(this.phone)) {
				uni.showToast({
					title: '请输入正确的手机号',
					icon: 'none'
				});
				return;
			}
			
			// 模拟发送验证码
			uni.showToast({
				title: '验证码已发送',
				icon: 'success'
			});
			
			// 开始倒计时
			this.codeCountdown = 60;
			this.codeTimer = setInterval(() => {
				this.codeCountdown--;
				if (this.codeCountdown <= 0) {
					clearInterval(this.codeTimer);
				}
			}, 1000);
		},
		
		// 切换协议同意状态
		toggleAgreement() {
			this.agreed = !this.agreed;
		},
		
		// 显示协议内容
		showAgreement(type) {
			const title = type === 'user' ? '用户协议' : '隐私政策';
			uni.showModal({
				title: title,
				content: `这里是${title}的内容...`,
				confirmText: '我知道了',
				showCancel: false
			});
		},
		
		// 表单验证
		validateForm() {
			if (!this.agreed) {
				uni.showToast({
					title: '请先同意用户协议和隐私政策',
					icon: 'none'
				});
				return false;
			}
			
			if (!this.phone) {
				uni.showToast({
					title: '请输入手机号',
					icon: 'none'
				});
				return false;
			}
			
			if (!/^1[3-9]\d{9}$/.test(this.phone)) {
				uni.showToast({
					title: '请输入正确的手机号',
					icon: 'none'
				});
				return false;
			}
			
			if (this.isLoginMode) {
				// 登录模式验证
				if (!this.password) {
					uni.showToast({
						title: '请输入密码',
						icon: 'none'
					});
					return false;
				}
			} else {
				// 注册模式验证
				if (!this.verifyCode) {
					uni.showToast({
						title: '请输入验证码',
						icon: 'none'
					});
					return false;
				}
				
				if (!this.password) {
					uni.showToast({
						title: '请设置密码',
						icon: 'none'
					});
					return false;
				}
				
				if (this.password.length < 6) {
					uni.showToast({
						title: '密码长度不能少于6位',
						icon: 'none'
					});
					return false;
				}
				
				if (this.password !== this.confirmPassword) {
					uni.showToast({
						title: '两次输入的密码不一致',
						icon: 'none'
					});
					return false;
				}
			}
			
			return true;
		},
		
		// 提交表单
		handleSubmit() {
			if (!this.validateForm()) return;
			
			// 显示加载状态
			uni.showLoading({
				title: this.isLoginMode ? '登录中...' : '注册中...'
			});
			
			// 模拟网络请求延迟
			setTimeout(() => {
				// 构造用户数据
				const userData = {
					phone: this.phone,
					nickName: `用户${this.phone.substr(-4)}`, // 使用手机号后4位作为昵称
					avatarUrl: 'https://img.icons8.com/fluency/48/user.png',
					gender: 0,
					city: '',
					province: '',
					country: '',
					language: 'zh_CN',
					loginTime: new Date().getTime(),
					loginType: 'phone',
					isRegistered: !this.isLoginMode // 标记是否为新注册用户
				};
				
				// 生成token
				const token = 'phone_token_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
				
				// 存储用户数据
				this.saveUserData(userData, token);
				
				// 登录成功处理
				this.loginSuccess(userData);
				
			}, 2000);
		},
		
		// 微信登录
		handleWechatLogin() {
			if (!this.agreed) {
				uni.showToast({
					title: '请先同意用户协议和隐私政策',
					icon: 'none'
				});
				return;
			}
			
			// 显示加载状态
			uni.showLoading({
				title: '微信登录中...'
			});
			
			// 微信登录流程
			this.doWechatLogin();
		},
		
		// 执行微信登录
		doWechatLogin() {
			// 第一步：微信登录获取code
			uni.login({
				provider: 'weixin',
				success: (loginRes) => {
					console.log('微信登录code：', loginRes.code);
					
					// 第二步：获取用户信息
					uni.getUserInfo({
						provider: 'weixin',
						success: (userRes) => {
							console.log('用户信息：', userRes.userInfo);
							
							// 构造用户数据
							const userData = {
								openid: 'mock_openid_' + Date.now(), // 实际应用中从服务器获取
								unionid: 'mock_unionid_' + Date.now(), // 实际应用中从服务器获取
								nickName: userRes.userInfo.nickName || '微信用户',
								avatarUrl: userRes.userInfo.avatarUrl || 'https://img.icons8.com/fluency/48/user.png',
								gender: userRes.userInfo.gender || 0,
								city: userRes.userInfo.city || '',
								province: userRes.userInfo.province || '',
								country: userRes.userInfo.country || '',
								language: userRes.userInfo.language || 'zh_CN',
								loginTime: new Date().getTime(),
								loginType: 'wechat'
							};
							
							// 生成token
							const token = 'wx_token_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
							
							// 存储用户信息和token
							this.saveUserData(userData, token);
							
							// 登录成功处理
							this.loginSuccess(userData);
						},
						fail: (err) => {
							console.error('获取用户信息失败：', err);
							uni.hideLoading();
							
							// 如果用户拒绝授权，使用默认信息
							if (err.errMsg && err.errMsg.indexOf('auth deny') !== -1) {
								this.handleAuthDeny(loginRes.code);
							} else {
								uni.showToast({
									title: '获取用户信息失败',
									icon: 'none'
								});
							}
						}
					});
				},
				fail: (err) => {
					console.error('微信登录失败：', err);
					uni.hideLoading();
					uni.showToast({
						title: '微信登录失败',
						icon: 'none'
					});
				}
			});
		},
		
		// 处理用户拒绝授权的情况
		handleAuthDeny(code) {
			uni.showModal({
				title: '提示',
				content: '检测到您拒绝了授权，将使用默认信息登录，您可以稍后在个人中心完善资料',
				confirmText: '继续登录',
				cancelText: '取消',
				success: (res) => {
					if (res.confirm) {
						// 使用默认用户信息
						const defaultUserData = {
							openid: 'default_openid_' + Date.now(),
							unionid: '',
							nickName: '微信用户',
							avatarUrl: 'https://img.icons8.com/fluency/48/user.png',
							gender: 0,
							city: '',
							province: '',
							country: '',
							language: 'zh_CN',
							loginTime: new Date().getTime(),
							loginType: 'wechat_default'
						};
						
						const token = 'wx_default_token_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
						
						// 存储默认用户信息
						this.saveUserData(defaultUserData, token);
						
						// 登录成功处理
						this.loginSuccess(defaultUserData);
					}
				}
			});
		},
		
		// 保存用户数据
		saveUserData(userData, token) {
			try {
				// 存储token
				uni.setStorageSync('token', token);
				
				// 存储用户信息
				uni.setStorageSync('userInfo', userData);
				
				// 设置登录状态
				uni.setStorageSync('isLoggedIn', true);
				
				// 存储登录时间
				uni.setStorageSync('loginTime', new Date().getTime());
				
				console.log('用户数据保存成功：', {
					token: token,
					userData: userData
				});
				
			} catch (e) {
				console.error('保存用户数据失败：', e);
				uni.showToast({
					title: '数据保存失败',
					icon: 'none'
				});
			}
		},
		
		// 登录成功处理
		loginSuccess(userData) {
			uni.hideLoading();
			
			// 显示欢迎信息
			uni.showToast({
				title: `欢迎您，${userData.nickName}！`,
				icon: 'success',
				duration: 2000
			});
			
			// 延迟跳转，让用户看到欢迎信息
			setTimeout(() => {
				// 跳转到首页并刷新tabbar状态
				uni.switchTab({
					url: '/pages/index/index',
					success: () => {
						console.log('跳转到首页成功');
						// 可以通过事件总线通知其他页面更新登录状态
						uni.$emit('loginStatusChanged', {
							isLoggedIn: true,
							userData: userData
						});
					}
				});
			}, 1500);
		},
		
		// 忘记密码
		goToForgotPassword() {
			uni.navigateTo({
				url: '/pages/forgot-password/forgot-password'
			});
		}
	}
}
</script>

<style scoped>
.login-container {
	background: linear-gradient(135deg, #c1d6f5 0%,#d0ddf1 50%, #f8f5f5 100%);
	/* background: #ffffff; */
	min-height: 100vh;
}

.main-content {
	padding: 40rpx;
	min-height: calc(100vh - 132px);
}

/* Logo区域 */
.logo-section {
	text-align: center;
	margin-bottom: 60rpx;
}

.app-logo {
	width: 180rpx;
	height: 180rpx;
	/* margin-bottom: 20rpx; */
}
.app-name {
	width: 280rpx;
	height: 180rpx;
	margin-bottom: 20rpx;
}


/* .app-name {
	display: block;
	font-size: 48rpx;
	font-weight: bold;
	margin-bottom: 10rpx;
} */

.app-slogan {
	display: block;
	font-size: 28rpx;
	color: rgba(255, 255, 255, 0.8);
}

/* 表单样式 */
.login-form {
	/* background: #ffffff; */
	/* border-radius: 20rpx; */
	padding: 40rpx;
	/* box-shadow: 0 8rpx 30rpx rgba(0, 0, 0, 0.1); */
}

.form-group {
	position: relative;
	margin-bottom: 30rpx;
	display: flex;
	align-items: center;
	background: #f8f9fa;
	border-radius: 50rpx;
	padding: 20rpx 30rpx;
}

.input-icon {
	width: 40rpx;
	height: 40rpx;
	margin-right: 20rpx;
	opacity: 0.6;
}

.input-field {
	flex: 1;
	font-size: 30rpx;
	color: #333;
	background: transparent;
	border: none;
}

.eye-icon {
	width: 36rpx;
	height: 36rpx;
	opacity: 0.6;
}

.code-btn {
	background: #667eea;
	border-radius: 30rpx;
	padding: 12rpx 24rpx;
	transition: all 0.3s ease;
}

.code-btn.disabled {
	background: #ccc;
}

.code-text {
	font-size: 24rpx;
	color: #ffffff;
}

.submit-btn {
	background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
	border-radius: 50rpx;
	padding: 30rpx;
	text-align: center;
	margin: 40rpx 0 30rpx 0;
	box-shadow: 0 8rpx 20rpx rgba(102, 126, 234, 0.3);
}

.btn-text {
	font-size: 32rpx;
	color: #ffffff;
	font-weight: bold;
}

.action-links {
	display: flex;
	justify-content: space-between;
	align-items: center;
}

.link-text {
	font-size: 26rpx;
	color: #667eea;
}

/* 分割线 */
.divider {
	display: flex;
	align-items: center;
	margin: 40rpx 0;
}

.divider-line {
	flex: 1;
	height: 1rpx;
	background: rgba(189, 186, 186, 0.3);
}

.divider-text {
	font-size: 24rpx;
	color: rgba(87, 83, 83, 0.3);
	margin: 0 30rpx;
}

/* 微信登录 */
.wechat-login {
	text-align: center;
}

.wechat-btn {
	/* background: #09bb07; */
	padding: 30rpx;
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	transition: all 0.3s ease;
}

.wechat-btn:active {
	transform: scale(0.98);
}

.wechat-icon {
	width: 64rpx;
	height: 64rpx;
	margin-right: 15rpx;
}

.wechat-text {
	padding-top: 10rpx;
	font-size: 30rpx;
	/* color: #ffffff; */
	/* font-weight: bold; */
}

/* 协议区域 */
.agreement-section {
	margin-top: 80rpx;
}

.agreement-check {
	display: flex;
	align-items: flex-start;
}

.check-icon {
	width: 36rpx;
	height: 36rpx;
	margin-right: 15rpx;
	margin-top: 2rpx;
}

.agreement-text {
	flex: 1;
	font-size: 24rpx;
	/* color: rgba(255, 255, 255, 0.8); */
	line-height: 1.5;
}

.link-style {
	color: #74bceb;
}
</style>